from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt

from myadmin import models
from .indexViews import getNavData


# 前台 - 购物车页面
def cartindex(request):
    # 检测是否登陆
    vipuser = request.session['vipUser']
    if len(vipuser) == 0:
        return HttpResponse(f'<script>alert("需要先登陆");history.back()</script>')

    # 获取用户对象
    userobj = models.Users.objects.get(id=vipuser['id'])

    context = {'classify':getNavData(),'userobj':userobj}
    return render(request,'myhome/cart.html',context)


# 购物车 - 添加商品
@csrf_exempt
def cartadd(request):
    # 接收ajax提交的数据
    data = request.POST.dict()
    # 检测是否登陆
    vipuser = request.session['vipUser']
    if not vipuser['id']:
        return JsonResponse({'code':1,'msg':'需要先登陆'})

    # 准备数据
    data['uid'] = models.Users.objects.get(id=vipuser['id'])
    data['bid'] = models.Books.objects.get(id=data['bid'])


    try:
        # 判断加入购物车的商品是否已经存在
        # 根据uid和bid获取cart类
        cart = data['uid'].cart_set.filter(bid=data['bid'])
        # 根据类的数量判断是否已经创建了cart对象，如果已经创建则直接增加num
        if cart.count():
            cartobj = cart[0]
            cartobj.num += int(data['num'])
            cartobj.save()
        else:
            # 把数据添加到购物车
            cartobj = models.Cart(**data)
            cartobj.save()
        return JsonResponse({'code':0,'msg':'加入购物车成功'})
    except:
        return JsonResponse({'code':2,'msg':'加入购物车失败'})


# 购物车 - 更新商品数量
def cartedit(request):
    # 接收编辑后的数量和购物车对象id
    cartid = request.GET.get('cartid')
    num = request.GET.get('n')
    try:
        # 获取购物车对象，更新数量
        cartobj = models.Cart.objects.get(id=cartid)
        cartobj.num = num
        cartobj.save()
        return JsonResponse({'code':0,'msg':'商品数量更新成功'})
    except:
        return JsonResponse({'code':1,'msg':'商品数量更新失败'})


# 购物车 - 删除商品
def cartdelete(request):
    cartid = request.GET.get('cartid')
    try:
        cartobj = models.Cart.objects.get(id=cartid)
        cartobj.delete()
        return JsonResponse({'code':0,'msg':'购物车商品删除成功'})
    except:
        return JsonResponse({'code':1,'msg':'购物车商品删除失败'})


















